<?php
/*
 * @Descripttion: 
 * @version: 
 * @Author: ewgof
 * @Date: 2020-09-24 20:04:45
 * @LastEditors: ewgof
 * @LastEditTime: 2020-10-06 10:49:02
 */
namespace app\http\controller\admin;

class Images extends Base
{
    // type: 图片归属，1：用户，2：游客
    public function index($request)
    {
        $type = $request->get('type', 1);
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 15);
        $num = ($page - 1) * $limit;
        
        $keywords = $request->get('keywords');
        $username = $request->get('username');

        $where = [];
        if (!empty($keywords)) {
            $where['OR'] = [
                'sha_md5[~]' => $keywords,
                'filename[~]' => $keywords,
                'mime[~]' => $keywords,
            ];
        }

        if ($type == 1) {
            $table = 'user_imgs';
            if (!empty($username)) {
                $where['uid'] = $this->db->get('users', 'id', ['username' => $username]);
            }
            $field = ['id', 'uid', 'url', 'filename', 'mime', 'sha_md5', 'views', 'created_at'];
        } elseif ($type == 2) {
            $table = 'guest_imgs';
            $field = ['id', 'url', 'filename', 'mime', 'sha_md5', 'views', 'created_at'];
        }
        $where['ORDER'] = ['created_at' => 'DESC'];
        $where['LIMIT'] = [$num, $num + $limit];

        $all = $this->db->count($table, $where);
        $list = $this->db->select($table, $field, $where);
        return api_json_return(0, '', ['all' => $all, 'list' => $list]);
    }



    // type: 图片归属，1：用户，2：游客
    public function deleteImg($request)
    {
        $id = $request->post('id');
        $type = $request->post('type');
        if (empty($id) || empty($type)) {
            return api_json_return(2);
        }
        if ($type == 1) {
            $table = 'user_imgs';
        } elseif ($type == 2) {
            $table = 'guest_imgs';
        }

        $img_urls = $this->db->select($table, 'url', ['id' => $id]);

        $info = $this->db->delete($table, ['id' => $id])->rowCount();
        if ($info) {
            foreach ($img_urls as $k => $v) {
                $img_path = __ROOT__ . ltrim(strstr($v, '/upload'), '/');
                @unlink($img_path);
            }
            return api_json_return(0);
        } else {
            $msg = '删除图片失败。id => ' . json_encode($id) . ', type => ' . $type . ', img_urls => ' . $img_urls . ', info => ' . $info;
            echo $msg . PHP_EOL;
            log_msg($msg, 'error', $this->log_filename_apperr);
            return api_json_return(1);
        }
    }
}
